<?php

namespace App\Http\Services;

use App\Http\Repositories\Daos\Project\ProjectDao;
use App\Http\Repositories\Daos\Task\SweepDao;
use App\Http\Requests\UserContext;
use App\Http\Traits\GlobalConstant;
use App\Models\Sweep;
use App\Models\TeamUser;
use Illuminate\Database\Eloquent\Builder;


class ProjectService extends BaseService
{
    protected $projectDao;
    protected $sweepDao;

    public function __construct(ProjectDao $projectDao, SweepDao $sweepDao)
    {
        $this->projectDao = $projectDao;
        $this->sweepDao   = $sweepDao;
    }

    /**
     * 项目列表-只有名称和id
     * @param UserContext $userContext
     * @return int|mixed
     */
    public function softLists()
    {
        $field           = ['id', 'name'];
        $where['status'] = 1;
        $order           = ['id' => 'desc'];
        $page            = request('page') ?? 1;
        $size            = request('size') ?? 10;
        return $this->projectDao->getListPage($where, $field, $page, $size, $order)->toArray();
    }

    /**
     * 轻详情，不带成员
     * @return mixed
     */
    public function softDetail()
    {
        $id              = request('p_id') ?? 0;
        $field           = ['id', 'name', 'desc', 'center_pos', 'address', 'province', 'city', 'district', 'lat', 'lng', 'coords', 'leader', 'leader_phone', 'state'];
        $where['status'] = 1;
        $where['id']     = $id;
        $info            = $this->projectDao->getOne($where, $field);
        if (!empty($info)) {
            $info['coords'] = GlobalConstant::formatAppCoords($info['coords']);
        }
        return $info;
    }

    public function lists(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 3;
        $offset = ($page * $size) - $size;
        $field  = ['project_id'];
        $where  = [
            'user_id' => $userId
        ];
        //使用teamuser而不使用sweep来统计是因为用户可能已经加入了队伍但没添加过sweep数据，但是还是要显示出参与的项目
        $list = TeamUser::where($where)
            ->whereHas('sweepInfo', function (Builder $q) {
                $q->select('project_id');
            })
            ->limit($size)->offset($offset)->with(["projectInfo" => function ($q) {
                $q->select(['id', 'name', 'leader', 'state']);
            }])
            ->groupBy('project_id')->get($field);
        if (!empty($list)) {
            foreach ($list as &$item) {
                $countObj            = $item->withCount(["sweepInfo" => function (Builder $q) use ($item) {
                    $q->where('project_id', $item['project_id']);
                }])->first();
                $item['sweep_count'] = $countObj->sweep_info_count;
                $item->name          = $item->projectInfo->name;
                $item->leader        = $item->projectInfo->leader;
                $item->state         = $item->projectInfo->state;
                unset($item->projectInfo);
                $sweep            = Sweep::where('project_id', $item['project_id'])->orderBy('updated_at', 'desc')->first();
                $item['sign_pic'] = $sweep['sign_pics'] ? $sweep['sign_pics'][0] : '';
                $item['time']     = $sweep['updated_at'];
            }
            unset($item);
        }
        return $list;
    }

    public function searchLists()
    {
        $key    = request('key_word') ?? '';
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $offset = ($page * $size) - $size;
        $field  = ['id', 'name', 'desc', 'center_pos', 'address', 'province', 'city', 'district', 'lat', 'lng', 'coords', 'leader', 'leader_phone'];
        $list   = $this->projectDao->getModel()
            ->where('name', 'like', '%' . $key . '%')
            ->orWhere('center_pos', 'like', '%' . $key . '%')
            ->orWhere('address', 'like', '%' . $key . '%')
            ->orWhere('province', 'like', '%' . $key . '%')
            ->orWhere('city', 'like', '%' . $key . '%')
            ->orWhere('district', 'like', '%' . $key . '%')
            ->orderBy('created_at', 'desc')
            ->limit($size)->offset($offset)->get($field);
        if (!empty($list)) {
            foreach ($list as &$item) {
                $item['coords'] = GlobalConstant::formatAppCoords($item['coords']);
            }
            unset($item);
        }
        return $list;
    }

    public function sweepList()
    {
        $projectId = request('p_id') ?? 0;
        $field     = ['id', 'project_id', 'sign_coord', 'sign_desc', 'sign_pics'];
        $list      = $this->sweepDao->getListPage(['project_id' => $projectId], $field);
        if (!empty($list)) {
            foreach ($list as &$item) {
                $entry_survey            = $item->entrySurvey;
                $item['entry_survey_id'] = $entry_survey ? $entry_survey['id'] : 0;
                unset($item->entrySurvey);
            }
            unset($item);
        }
        return $list;
    }

}
